package com.ruoyi.system.service.impl;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.WaterCostMapper;
import com.ruoyi.system.mapper.WaterMeterMapper;
import com.ruoyi.system.service.ISysFloorService;
import com.ruoyi.system.service.IWaterCostService;
import com.ruoyi.system.service.IWaterMeterService;
import com.ruoyi.system.service.ITenantInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WaterCostServiceImpl implements IWaterCostService {
    @Autowired
    private WaterCostMapper waterCostMapper;

    @Autowired
    private ITenantInfoService tenantInfoService;

    @Autowired
    private WaterMeterMapper waterMeterMapper;

    @Autowired
    private ISysFloorService sysFloorService;

    @Override
    public List<SjWaterCost> selectWaterCostList(SjWaterCost sjWaterCost) {
        return waterCostMapper.selectWaterCostList(sjWaterCost);
    }

    @Override
    public int deleteWaterByEtldt(String etldt) {
        return waterCostMapper.deleteWaterByEtldt(etldt);
    }

    @Override
    public AjaxResult generateWater(String etldt, List<SysFloor> floorInfos) {
        StringBuilder message = new StringBuilder();
        for (SysFloor sysFloor:floorInfos){
           SjWaterMeter sjWaterMeter = new SjWaterMeter();
           sjWaterMeter.setEtldt(etldt);
           sjWaterMeter.setFloorName(sysFloor.getFloorName());
           SjWaterMeter sjwm = waterMeterMapper.selectWaterMeterByFloorAndEtldt(sjWaterMeter);
           if (sjwm == null) {
               message.append("缺少"+etldt+"批次"+sysFloor.getFloorName()+"楼层的抄表记录</br>");
               continue;
           }
           TenantInfo tenantInfo = new TenantInfo();
           tenantInfo.setTenantFloor(sysFloor.getFloorName());
           List<TenantInfo> tenantInfos = tenantInfoService.selectTenantInfoList(tenantInfo);
           if(tenantInfos!=null&&tenantInfos.size()>1){
               //直接公摊
               Double allWater = sjwm.getDegreeA()+sjwm.getDegreeB()+Double.valueOf(StringUtils.isBlank(sysFloor.getFireAirCondition())?"0.00":sysFloor.getFireAirCondition());
               Double allArea = tenantInfoService.selectSumFloorArea(sysFloor.getFloorName());  //楼层总面积
               for(TenantInfo ti:tenantInfos){
                   Double tenantArea = ((ti.getTenantArea()==null)?0.00:ti.getTenantArea().doubleValue()) + ((ti.getEmptyArea()==null)?0.00:ti.getEmptyArea().doubleValue());
                   Double tenantWater = tenantArea/allArea*allWater;
                   insertWaterCost(sysFloor,ti,tenantWater,etldt);
           }
       }else{
               //楼层单租户
               if(tenantInfos.size()==1){  //楼层有租户
                   TenantInfo tenant = tenantInfos.get(0);
                   Double allWater = sjwm.getDegreeA()+sjwm.getDegreeB()+Double.valueOf(StringUtils.isBlank(sysFloor.getFireAirCondition())?"0.00":sysFloor.getFireAirCondition());
                   insertWaterCost(sysFloor,tenant,allWater,etldt);
               }
           }
        }
        return AjaxResult.success();
   }

    @Override
    public String importWaterCost(List<SjWaterCost> sjWaterCostList) {
        int size = 0;
        if(sjWaterCostList!=null){
            size = sjWaterCostList.size();
        }
        int errorData = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        StringBuilder errorDatas = new StringBuilder();
        String etldt = "";
        DecimalFormat dec = new DecimalFormat("#0.00");
        if(sjWaterCostList!=null&&sjWaterCostList.size()>0){
            try {
                etldt = sjWaterCostList.get(0).getEtldt();
                sdf.parse(etldt);
            } catch (ParseException e) {
                throw new BusinessException("日期格式不正确");
            }
            //删除之前数据  重新生成？
            waterCostMapper.deleteWaterByEtldt(etldt);
        }
        int count = 0;
        for(SjWaterCost sjWaterCost:sjWaterCostList){
            count++;
            try {
                sdf.parse(sjWaterCost.getEtldt());
            } catch (ParseException e) {
                errorData++;
                String errStr = "第"+count+"行,缺少水费批次或日期格式不正确；</br>";
                errorDatas.append(errStr);
                continue;
            }
            if(!etldt.equals(sjWaterCost.getEtldt())){
                errorData++;
                String errStr = "第"+count+"行,日期不统一；</br>";
                errorDatas.append(errStr);
                continue;
            }
            if(StringUtils.isEmpty(sjWaterCost.getFloorName())){
                errorData++;
                String errStr = "第"+count+"行,未填写楼层；</br>";
                errorDatas.append(errStr);
                continue;
            }
            if(StringUtils.isEmpty(sjWaterCost.getTenantName())){
                errorData++;
                String errStr = "第"+count+"行,未填写租户；</br>";
                errorDatas.append(errStr);
                continue;
            }
            if(sjWaterCost.getContributionDegree()==null){
               /* errorData++;
                String errStr = "第"+count+"行,未填写用水量；</br>";
                errorDatas.append(errStr);
                continue;*/
                sjWaterCost.setContributionDegree(0.0);
            }
            SysFloor sysFloor = sysFloorService.selectSysFloorByName(sjWaterCost.getFloorName());
            if(sysFloor==null){
                errorData++;
                String errStr = "第"+count+"行,未找到楼层"+sjWaterCost.getFloorName()+"；</br>";
                errorDatas.append(errStr);
                continue;
            }
            //计算水费？
            Double tenantWater = sjWaterCost.getContributionDegree();
            String waterParam = sysFloor.getWaterParam();
            Double waterCost = Double.valueOf(waterParam)*tenantWater;
            sjWaterCost.setWaterCost(waterCost);

            sjWaterCost.setCreateTime(new Date());
            sjWaterCost.setWaterId(UUID.randomUUID().toString().replaceAll("-",""));
            sjWaterCost.setNum(count);
            waterCostMapper.insertWaterCost(sjWaterCost);
        }
        String message;
        if(size>0){
            message = "共导入"+size+"条数据。</br>";
        }else{
            return "无数据";
        }
        if(StringUtils.isNotEmpty(errorDatas.toString())){
            message = message + "其中" + errorData + "条数据导入失败，错误原因如下：</br>";
            message = message + errorDatas.toString();
        }
        return message;
    }

    public void insertWaterCost(SysFloor sysFloor,TenantInfo tenant,Double tenantWater,String etldt){
        SjWaterCost sjWaterCost = new SjWaterCost();
        sjWaterCost.setFloorName(tenant.getTenantFloor());
        sjWaterCost.setTenantId(tenant.getTenantId());
        sjWaterCost.setTenantName(tenant.getTenantName());
        sjWaterCost.setContributionDegree(tenantWater);
        sjWaterCost.setEtldt(etldt);
        sjWaterCost.setWaterId(UUID.randomUUID().toString().replaceAll("-",""));
        if(!tenant.getCharges().contains("1")){
            tenantWater = 0.0;
        }
        Double chargeCoe = tenant.getChargeCoefficient();//收费系数
        //计算水费
        String unitPrice = sysFloor.getWaterParam();
        Double waterFee = Double.valueOf(unitPrice)*tenantWater*chargeCoe;
        sjWaterCost.setWaterCost(waterFee);
        waterCostMapper.insertWaterCost(sjWaterCost);
    }

    @Override
    public List<SjWaterCost> exportWaterCost(SjWaterCost sjWaterCost) {
        List<SjWaterCost> list = waterCostMapper.selectWaterCostList(sjWaterCost);
        SjWaterCost sumSjWaterCost = new SjWaterCost();
        sumSjWaterCost.setFloorName("合计");
        Double contributionDegree = 0.0;
        Double waterCost = 0.0;
        for (SjWaterCost sjwc:list){
            if (sjwc.getContributionDegree()!=null){
                contributionDegree += sjwc.getContributionDegree();
            }
            if (sjwc.getWaterCost()!=null){
                waterCost += sjwc.getWaterCost();
            }
        }
        sumSjWaterCost.setContributionDegree(contributionDegree);
        sumSjWaterCost.setWaterCost(waterCost);
        if (list!=null){
            list.add(sumSjWaterCost);
        }
        return list;
    }
}
